import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:mybase/base/animator/FFAnimatorBaseWidget.dart';
import 'package:mybase/base/super/FFInk.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'package:mybase/base/widget/layout/FFBranch.dart';
import 'package:mybase/base/widget/layout/FFImageButton.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webview_window_example/textField/FFTextField.dart';

class SelectMdMapWindow extends StatefulWidget {
  String mapFile;
  Function(String str)? onFinish;

  SelectMdMapWindow({
    Key? key,
    required this.mapFile,
    this.onFinish,
  }) : super(key: key);

  @override
  SelectMdMapWindowState createState() {
    return SelectMdMapWindowState();
  }
}

class SelectMdMapWindowState extends State<SelectMdMapWindow> {
  List<SelectMdEntity> list = [];
  List<SelectMdEntity> searchResultList = [];
  TextEditingController controller = TextEditingController();

  bool isSearching = false;
  String searchKey = "";

  @override
  void initState() {
    super.initState();
    handleOutputFile();
  }

  handleOutputFile() async {
    //生成md5.json的内容
    String mapFileContent = await FFile.readAsString(widget.mapFile);
    Map<String, dynamic> targetMap = {};
    Map<String, dynamic> mapObj = json.decode(mapFileContent);

    convertFile("", mapObj, targetMap);

    list = [];
    targetMap.forEach((key, value) {
      list.add(SelectMdEntity(
          md5Str: key, value: value, md5ToName: "", index: list.length));
    });
    setState(() {});
  }

  void convertFile(String outKey, Map<String, dynamic> mapObj,
      Map<String, dynamic> targetMap) {
    mapObj.forEach((key, value) {
      String inKey = md5.convert(utf8.encode("$outKey$key")).toString();
      if (value is String) {
        targetMap[inKey] = value;
      } else if (value is Map) {
        Map<String, dynamic> valueMap = value as Map<String, dynamic>;
        convertFile(inKey, valueMap, targetMap);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height * 0.8,
      color: isSearching == false ? Colors.black : Colors.green,
      padding: const EdgeInsets.only(bottom: 16),
      child: FFLineContainer(
        direction: Axis.vertical,
        children: [
          FFLineContainer(
            heigth: 46,
            crossAxisAlignment: CrossAxisAlignment.center,
            color: Colors.red,
            direction: Axis.horizontal,
            children: [
              FFInk(
                child: FFTextButton(
                  text: "确定",
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  fontColor: Colors.green,
                  onClick: () {
                    Map<String, dynamic> map = {};
                    for (int i = 0; i < list.length; i++) {
                      SelectMdEntity entity = list[i];
                      if (entity.selected == true) {
                        map[entity.md5Str!] = entity.value;
                      }
                    }

                    if (!FFEmpty.mapIsEmpty(map)) {
                      String mapstr = json.encode(map);
                      if (widget.onFinish != null) {
                        widget.onFinish!(mapstr);
                      }
                    }

                    SmartDialog.dismiss();
                  },
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              FFInk(
                child: FFTextButton(
                  text: "取消所有选择",
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  fontColor: Colors.green,
                  onClick: () {
                    for (int i = 0; i < list.length; i++) {
                      SelectMdEntity entity = list[i];
                      entity.selected = false;
                    }
                    setState(() {});
                  },
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              FFLineContainer(
                heigth: 40,
                direction: Axis.horizontal,
                margin: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                  color: Colors.pink,
                ),
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const SizedBox(
                    width: 12,
                  ),
                  Container(
                    height: 30,
                    width: 240,
                    child: FFTextField(
                      needCancelBtn: false,
                      controller: controller,
                      onValid: (bool valid, String value) {
                        searchKey = value;
                        isSearching = !FFEmpty.stringIsEmpty(value);
                        searchResultList = [];

                        if (isSearching == true) {
                          for (int i = 0; i < list.length; i++) {
                            SelectMdEntity entity = list[i];
                            if (FFEmpty.stringIsEmpty(entity.value)) {
                              continue;
                            }
                            if (entity.value!
                                .toLowerCase()
                                .contains(value.toLowerCase())) {
                              searchResultList.add(entity);
                            }
                          }
                        }

                        setState(() {});
                      },
                      min: 0,
                      max: 99999,
                    ),
                  ),
                  FFInk(
                    child: FFTextButton(
                      hiddenKeepFrame: !isSearching,
                      text: "取消搜索",
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      fontColor: Colors.green,
                      onClick: () {
                        controller.text = "";
                        isSearching = false;
                        setState(() {});
                      },
                    ),
                  )
                ],
              ),
              FFInk(
                child: FFTextButton(
                  text: "全选",
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  fontColor: Colors.green,
                  onClick: () {
                    controller.text = "";
                    isSearching = false;
                    for (int i = 0; i < list.length; i++) {
                      SelectMdEntity entity = list[i];
                      entity.selected = true;
                    }
                    setState(() {});
                  },
                ),
              ),
            ],
          ),
          Expanded(
            child: FFBranch(
              condition: isSearching,
              trueWidget: ListView.builder(
                itemBuilder: (ctx, i) {
                  SelectMdEntity entity = searchResultList[i];
                  return FFInk(
                    child: FFLineContainer(
                      onClick: () {
                        entity.selected = !(entity.selected ?? false);
                        setState(() {});
                      },
                      direction: Axis.horizontal,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1.0,
                                  color: Colors.white.withAlpha(100))),
                          color: entity.selected == true
                              ? Colors.pink.withAlpha(140)
                              : Colors.transparent),
                      children: [
                        FFTextButton(
                          text: "<${entity.index}> ${entity.md5Str}",
                          fontSize: 14,
                          fontColor: Colors.white,
                          width: 330,
                        ),
                        Expanded(
                          child: FFTextButton(
                            text: entity.value,
                            fontSize: 14,
                            fontColor: Colors.white,
                            maxLines: 1000,
                          ),
                        ),
                      ],
                    ),
                  );
                },
                itemCount: searchResultList.length,
              ),
              falseWidget: ListView.builder(
                itemBuilder: (ctx, i) {
                  SelectMdEntity entity = list[i];
                  return FFInk(
                    child: FFLineContainer(
                      onClick: () {
                        entity.selected = !(entity.selected ?? false);
                        setState(() {});
                      },
                      direction: Axis.horizontal,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 8),
                      decoration: BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1.0,
                                  color: Colors.white.withAlpha(100))),
                          color: entity.selected == true
                              ? Colors.pink.withAlpha(140)
                              : Colors.transparent),
                      children: [
                        FFTextButton(
                          text: "<${entity.index}> ${entity.md5Str}",
                          fontSize: 14,
                          fontColor: Colors.white,
                          width: 330,
                        ),
                        Expanded(
                          child: FFTextButton(
                            text: entity.value,
                            fontSize: 14,
                            fontColor: Colors.white,
                            maxLines: 1000,
                          ),
                        ),
                      ],
                    ),
                  );
                },
                itemCount: list.length,
              ),
            ),
          )
        ],
      ),
    );
  }
}

class SelectMdEntity {
  String? md5Str;
  String? value;
  String? md5ToName;
  bool? selected;
  int? index;

  SelectMdEntity({
    this.md5Str,
    this.value,
    this.md5ToName,
    this.selected,
    this.index,
  });
}
